﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxCallback;
using System.Configuration;

namespace TireService.Web.UserControls
{
    public partial class ucEditCustomerInvoice : System.Web.UI.UserControl
    {
        private string _controlname = "EditCustomerInvoice";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Convert.ToBoolean(Session["UserControlLoaded" + _controlname]))
            {
                // Initiate datalayer
                TireServiceDB db = new TireServiceDB();

                // Show customer invoices
                LoadCustomerInvoice(Convert.ToInt32(Session["CustomerId" + _controlname]));
            }
        }

        protected void callbackEditCustomerInvoicePanel_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            Session["CustomerId" + _controlname] = Convert.ToInt32(e.Parameter);

            LoadUserControl(Convert.ToInt32(e.Parameter));
        }

        /// <summary>
        /// Callback function that send customer email with invoice and paymentlink
        /// </summary>
        protected void callSendInvoiceByEmail_Callback(object sender, CallbackEventArgs e)
        {
            // Get client input (0: Invoiceid, 1: Action (0: Send invoice, 1: Send reminder))
            string[] param = e.Parameter.Split('|');


            int InvoiceId = Convert.ToInt32(param[0]);
            int Action = Convert.ToInt32(param[1]);


            // Validate invoice
            EconomicInterface ecoInterface = new EconomicInterface();
            if (!ecoInterface.InvoiceLinesExists(InvoiceId))
            {
                throw new ArgumentException("Betaling kan ikke finde sted, da faktura ikke eksisterer - venligst kontakt vores kundesupport.");
            }
            else
            {
                // Check if invoice is already paid
                decimal? invoiceremainder = ecoInterface.GetInvoiceRemainder(InvoiceId);

                if (invoiceremainder > 0 & invoiceremainder != null)
                {
                    // Get customerid
                    int CustomerId = ecoInterface.GetCustomerIdByInvoice(InvoiceId);

                    // Instantiate database
                    TireServiceDB db = new TireServiceDB();

                    // Get customer
                    Customer customer = db.GetCustomer(CustomerId);

                    // Prepare email
                    EmailNotificationServices emailService = new EmailNotificationServices();

                    if (Action == 0)
                    {
                        // Send email with invoice and link to payment    
                        emailService.Customer_Invoice_SendCustomerEmail(customer.CustomerId, customer.Email, customer.Name, InvoiceId.ToString(), ecoInterface.GetInvoice(InvoiceId), "Faktura" + InvoiceId.ToString() + ".pdf", Convert.ToString((int)Shared.PaymentGateWayActions.InitiatePayment), Convert.ToString(ConfigurationManager.AppSettings["AcceptURL"]));
                    }
                    if (Action == 1)
                    {
                        // Send invoice reminder and link to payment
                        emailService.Customer_InvoiceReminder_SendCustomerEmail(customer.CustomerId, customer.Email, customer.Name, InvoiceId.ToString(), ecoInterface.GetInvoice(InvoiceId), "Faktura" + InvoiceId.ToString() + ".pdf", Convert.ToString((int)Shared.PaymentGateWayActions.InitiatePayment), Convert.ToString(ConfigurationManager.AppSettings["AcceptURL"]));
                    }
                }
                else
                {
                    throw new ArgumentException("Faktura er betalt.");
                }
            }
        }

        /// <summary>
        /// Public function for loading usercontrol
        /// </summary>
        public void LoadUserControl(int CustomerId)
        {
            // Initiate datalayer
            TireServiceDB db = new TireServiceDB();

            if (CustomerId != 0)
            {
                // Show customer invoices
                LoadCustomerInvoice(CustomerId);
            }
            else
            {
                // Error
                throw new ArgumentException("Kunde ikke fundet");
            }

            // Dispose connection to database
            db.Dispose();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="CustomerId"></param>
        public void LoadCustomerInvoice(int CustomerId) 
        {
            // Load invoices from e-conomic
            EconomicInterface ecoInterface = new EconomicInterface();
            gvInvoice.DataSource = ecoInterface.GetCustomerInvoiceList(CustomerId); //db.GetCustomerInvoices(this.CustomerId);
            gvInvoice.DataBind();

            Session["UserControlLoaded" + _controlname] = true;
        }
    }
}